package com.movie.service.impl;

import com.movie.model.Movie;
import com.movie.model.Screening;
import com.movie.service.AdminService;
import com.movie.util.DataUtil;

import java.util.List;

public class AdminServiceImpl implements AdminService {
    private List<Movie> movies;
    private List<Screening> screenings;
    private DataUtil dataUtil;

    public AdminServiceImpl(DataUtil dataUtil) {
        this.dataUtil = dataUtil;
        loadData();
    }

    private void loadData(){
        this.movies = dataUtil.loadMovies();
        this.screenings = dataUtil.loadScreenings();
    }

    private void saveData(){
        dataUtil.saveMovies(movies);
        dataUtil.saveScreenings(screenings);
    }

    @Override
    public void addMovie(Movie movie) {
        movies.add(movie);
        saveData();
    }

    @Override
    public void updateMovie(Movie movie) {
        for (int i = 0; i < movies.size(); i++) {
            if(movies.get(i).getId().equals(movie.getId())){
                movies.set(i,movie);
                saveData();
                return;
            }
        }
    }

    @Override
    public void deleteMovie(String movieId) {
        movies.removeIf(movie -> movie.getId().equals(movieId));
        saveData();
    }

    @Override
    public List<Movie> getAllMovies() {
        return movies;
    }

    @Override
    public void addScreening(Screening screening) {
        screenings.add(screening);
        saveData();
    }

    @Override
    public void updateScreening(Screening screening) {
        for (int i = 0; i < screenings.size(); i++) {
            if(screenings.get(i).getId().equals(screening.getId())){
                screenings.set(i,screening);
                saveData();
                return;
            }
        }
    }

    @Override
    public void deleteScreening(String screeningId) {
        screenings.removeIf(screening -> screening.getId().equals(screeningId));
        saveData();
    }

    @Override
    public List<Screening> getAllScreenings() {
        return screenings;
    }
}